package com.csun.cmny.provider.resolver;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2018-12-28 13:28
 * @Description:
 */
@Slf4j
public class CmnyLocaleResolver implements LocaleResolver {

    private static final String HEADER_LANGUAGE = "Accept-Language";

    private static final String I18N_LANGUAGE = "i18n_language";
    private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String param = request.getHeader(HEADER_LANGUAGE);
//        String i18n_language = request.getParameter(I18N_LANGUAGE);
//        Locale locale = Locale.getDefault();
//
//        if (StringUtils.isNotEmpty(i18n_language)) {
//            String[] language = i18n_language.split("_");
//            locale = new Locale(language[0], language[1]);
//
//            //将国际化语言保存到session
//            HttpSession session = request.getSession();
//            session.setAttribute(I18N_LANGUAGE_SESSION, locale);
//        }else {
//            //如果没有带国际化参数，则判断session有没有保存，有保存，则使用保存的，也就是之前设置的，避免之后的请求不带国际化参数造成语言显示不对
//            HttpSession session = request.getSession();
//            Locale localeInSession = (Locale) session.getAttribute(I18N_LANGUAGE_SESSION);
//            if(localeInSession != null) {
//                locale = localeInSession;
//            }
//        }
        Locale locale = Locale.getDefault();
        log.debug("default local = {}", locale.toString());
        if (StringUtils.isNotEmpty(param)) {
            log.debug("Accept-Language = {}", param);
            String[] language = param.split("_");
            if (language.length == 2) {
                locale = new Locale(language[0], language[1]);
                log.debug("current local = {}", locale.toString());
            }
        } else {
            locale = new Locale("zh", "CN");
        }
        LocaleContextHolder.setLocale(locale);

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
